package dao;

import bean.Bean;

import java.util.Objects;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class BeanDAOImpl implements BeanDAO {
    private SqlSessionFactory factory;
    private static SqlSession session;
    private boolean status;

    public BeanDAOImpl(SqlSessionFactory factory) {
        this.factory = factory;
    }
    
    public void open() {
        session = factory.openSession();
    }

    @Override
    public boolean add(Bean bean) {
        try {
            open();
            /*
             * “ns.a”表示命名空间为t的mapper中id为a的dml关键词元素
             * （insert、update、delete或select）内部的sql语句
             * bean必须是sql语句元素中的parameterType属性值代表的非限定类名的实例
             */
            int insert = session.insert("ns.a", bean);
            // 在运行sql语句后执行提交（commit）操作
            session.commit();
            status = insert != 0;
        } catch (Exception e) {
            status = false;
            e.printStackTrace();
        }
        if (Objects.nonNull(session))
            session.close();
        return status;
    }

    @Override
    public boolean modify(Bean bean) {
        try {
            open();
            int update = session.update("ns.m", bean);
            session.commit();
            status = update != 0;
        } catch (Exception e) {
            status = false;
            e.printStackTrace();
        }
        if (Objects.nonNull(session))
            session.close();
        return status;
    }

    @Override
    public boolean remove(int key) {
        try {
            open();
            int delete = session.delete("ns.r", key);
            session.commit();
            status = delete != 0;
        } catch (Exception e) {
            status = false;
            e.printStackTrace();
        }
        if (Objects.nonNull(session))
            session.close();
        return status;
    }

    @Override
    public Bean find(int key) {
        Bean bean;
        try {
            open();
            bean = session.selectOne("ns.s", key);
        } catch (Exception e) {
            bean = null;
            e.printStackTrace();
        }
        if (Objects.nonNull(session))
            session.close();
        return bean;
    }
}
